package config

import (
	"GOPAAS/internal/app/global"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"path/filepath"
	"strings"
)

type Config struct {
	Host               string `yaml:"host"`
	AppName            string `yaml:"app-name"`
	Port               int    `yaml:"port"`
	DataDir            string `yaml:"data-dir"`
	SessionKey         string `yaml:"session-key"`
	UploaderPath       string `yaml:"uploader-path"`
	DtcloudPath        string `yaml:"dtcloud-path"`
	PreviewPath        string `yaml:"preview-path"`
	AliAccessKeyId     string `yaml:"ali-access-key-id"`
	AliAccessKeySecret string `yaml:"ali-access-key-secret"`
	AliSmsSignName     string `yaml:"ali-sms-sign-name"`
	DefaultPassword    string `yaml:"default-password"`
	SocketUrl          string `yaml:"socket-url"`
	Jiguang            JiguangConfig
	Database           DbConfigs
}

type JiguangConfig struct {
	AppKey       string `yaml:"app-key"`
	Channel      string `yaml:"channel"`
	MasterSecret string `yaml:"master-secret"`
}

var Conf = Config{}

func ConfInit(configName string) Config {
	viper.SetConfigName(configName)  // 配置文件名 (不带扩展格式)
	viper.AddConfigPath("./configs") // 配置文件的路径

	err := viper.ReadInConfig() //找到并读取配置文件
	if err != nil {             // 捕获读取中遇到的error
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	}
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		config_name := filepath.Base(e.Name)
		config_name = strings.TrimRight(config_name, ".yaml")
		viper.SetConfigName(config_name) // 配置文件名 (不带扩展格式)
		err := viper.ReadInConfig()      //找到并读取配置文件
		if err != nil {                  // 捕获读取中遇到的error
			panic(fmt.Errorf("Fatal error config file: %w \n", err))
		}
		Conf = GetConfigData()
		global.ReloadDatabase = true
	})
	Conf = GetConfigData()
	viper.WatchConfig()
	return Conf
}
func GetConfigData() Config {
	app_name := viper.GetString("app-name")
	fmt.Println(app_name)
	return Config{
		AppName:         viper.GetString("app-name"),
		SocketUrl:       viper.GetString("socket-url"),
		SessionKey:      viper.GetString("session-key"),
		Port:            viper.GetInt("port"),
		DataDir:         viper.GetString("data-dir"),
		DefaultPassword: viper.GetString("default-password"),
		UploaderPath:    viper.GetString("uploader-path"),
		DtcloudPath:     viper.GetString("dtcloud-path"),
		PreviewPath:     viper.GetString("preview-path"),

		AliAccessKeyId:     viper.GetString("ali-access-key-id"),
		AliAccessKeySecret: viper.GetString("ali-access-key-secret"),
		AliSmsSignName:     viper.GetString("ali-sms-sign-name"),
		Jiguang: JiguangConfig{
			AppKey:       viper.GetString("jiguang.app-key"),
			Channel:      viper.GetString("jiguang.channel"),
			MasterSecret: viper.GetString("jiguang.master-secret"),
		},
		Database: DbConfigs{
			"postgresql": GetDBConfigData("database.postgresql"),
		},
	}
}
